<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="冗余字段" prop="typeIds">
        <el-input
          v-model="queryParams.typeIds"
          placeholder="请输入冗余字段"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品主图" prop="img">
        <el-input
          v-model="queryParams.img"
          placeholder="请输入商品主图"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品评论数" prop="commentCount">
        <el-input
          v-model="queryParams.commentCount"
          placeholder="请输入商品评论数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品收藏人气" prop="collectCount">
        <el-input
          v-model="queryParams.collectCount"
          placeholder="请输入商品收藏人气"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌信息" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单位"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="搜索关键字" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入搜索关键字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格信息" prop="ruleId">
        <el-input
          v-model="queryParams.ruleId"
          placeholder="请输入规格信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="乐观锁" prop="revision">
        <el-input
          v-model="queryParams.revision"
          placeholder="请输入乐观锁"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="0：添加商品信息 1：添加规格信息 2：添加描述信息" prop="step">
        <el-input
          v-model="queryParams.step"
          placeholder="请输入0：添加商品信息 1：添加规格信息 2：添加描述信息"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['product:productInfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:productInfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:productInfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['product:productInfo:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品描述" align="center" prop="productDesc" />
      <el-table-column label="商品类型" align="center" prop="type" />
      <el-table-column label="冗余字段" align="center" prop="typeIds" />
      <el-table-column label="商品主图" align="center" prop="img" />
      <el-table-column label="商品轮播图" align="center" prop="carouselImages" />
      <el-table-column label="商品评论数" align="center" prop="commentCount" />
      <el-table-column label="商品收藏人气" align="center" prop="collectCount" />
      <el-table-column label="品牌信息" align="center" prop="brand" />
      <el-table-column label="商品状态" align="center" prop="status" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="搜索关键字" align="center" prop="keyword" />
      <el-table-column label="规格信息" align="center" prop="ruleId" />
      <el-table-column label="乐观锁" align="center" prop="revision" />
      <el-table-column label="0：添加商品信息 1：添加规格信息 2：添加描述信息" align="center" prop="step" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['product:productInfo:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['product:productInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productInfoRef" :model="form" :rules="rules" label-width="80px">
        <el-steps :active="active" finish-status="success">
          <el-step title="添加商品信息"></el-step>
          <el-step title="添加规格信息"></el-step>
          <el-step title="添加描述信息"></el-step>
        </el-steps>

        <div v-show="active==0">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="商品名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入商品名称"/>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="单位" prop="unit">
                  <el-input v-model="form.unit" placeholder="请输入单位" />
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="品牌信息" prop="brand">
                  <template>
                    <el-select v-model="form.brand" placeholder="请选择品牌信息">
                      <el-option
                          v-for="item in brandList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </template>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="分类" prop="type">
                  <el-cascader
                      v-model="form.type"
                      placeholder="请选择分类"
                      :options="categoryList"
                      :props="{ expandTrigger: 'hover', value: 'catId', label: 'name', children: 'childrenList' }"
                  >
                  </el-cascader>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-form-item label="商品主图" prop="img">
            <ImageUpload v-model="form.img"></ImageUpload>
          </el-form-item>
          <el-form-item label="商品轮播图" prop="carouselImages">
            <ImageUpload v-model="form.carouselImages"></ImageUpload>
          </el-form-item>
        </div>


<!--        <el-form-item label="商品名称" prop="name">-->
<!--          <el-input v-model="form.name" placeholder="请输入商品名称" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="商品描述" prop="productDesc">-->
<!--          <el-input v-model="form.productDesc" type="textarea" placeholder="请输入内容" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="冗余字段" prop="typeIds">-->
<!--          <el-input v-model="form.typeIds" placeholder="请输入冗余字段" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="商品主图" prop="img">-->
<!--          <image-upload v-model="form.img"/>-->
<!--        </el-form-item>-->
<!--&lt;!&ndash;        <el-form-item label="商品主图" prop="img">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-input v-model="form.img" placeholder="请输入商品主图" />&ndash;&gt;-->
<!--&lt;!&ndash;        </el-form-item>&ndash;&gt;-->
<!--        <el-form-item label="商品轮播图" prop="carouselImages">-->
<!--          <image-upload v-model="form.carouselImages"/>-->
<!--        </el-form-item>-->
<!--&lt;!&ndash;        <el-form-item label="商品轮播图" prop="carouselImages">&ndash;&gt;-->
<!--&lt;!&ndash;          <el-input v-model="form.carouselImages" type="textarea" placeholder="请输入内容" />&ndash;&gt;-->
<!--&lt;!&ndash;        </el-form-item>&ndash;&gt;-->
<!--        <el-form-item label="商品评论数" prop="commentCount">-->
<!--          <el-input v-model="form.commentCount" placeholder="请输入商品评论数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="商品收藏人气" prop="collectCount">-->
<!--          <el-input v-model="form.collectCount" placeholder="请输入商品收藏人气" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="品牌信息" prop="brand">-->
<!--          <el-input v-model="form.brand" placeholder="请输入品牌信息" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="单位" prop="unit">-->
<!--          <el-input v-model="form.unit" placeholder="请输入单位" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="搜索关键字" prop="keyword">-->
<!--          <el-input v-model="form.keyword" placeholder="请输入搜索关键字" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="规格信息" prop="ruleId">-->
<!--          <el-input v-model="form.ruleId" placeholder="请输入规格信息" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="乐观锁" prop="revision">-->
<!--          <el-input v-model="form.revision" placeholder="请输入乐观锁" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="0：添加商品信息 1：添加规格信息 2：添加描述信息" prop="step">-->
<!--          <el-input v-model="form.step" placeholder="请输入0：添加商品信息 1：添加规格信息 2：添加描述信息" />-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductInfo">
import { listProductInfo, getProductInfo, delProductInfo, addProductInfo, updateProductInfo } from "@/api/product/productInfo";

const { proxy } = getCurrentInstance();

const productInfoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({

  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    productDesc: null,
    type: null,
    typeIds: null,
    img: null,
    carouselImages: null,
    commentCount: null,
    collectCount: null,
    brand: null,
    status: null,
    unit: null,
    keywords: null,
    ruleId: null,
    revision: null,
    step: null
  },
  //表单参数
  form: {},
  rules: {
  },
  stepMap:{
    0:'添加商品信息',
    1:'添加规格信息',
    2:'添加描述信息',
  },
  active:0,
  brandList:[],
  categoryList:[],
  ruleInfoList:[],
  tableColumnHeaderTemplate:[],
  tableBodyTemplate:[
    // {'stock':'商品库存',price:"1",purchasePrice: "1",sellingPrice: "1",image :"",weight:"1",volume:"1"},
  ],
  skuFormTemplate:{'stock':'商品库存',price:"0",purchasePrice: "0",sellingPrice: "0",image :"",number :"0",weight:"0",volume:"0"},
  created() {
    this.initListRuleInfo()
    this.initCategoryList();
    this.initBrandList();
    this.getList();
  },
  updateProductStatus(object){
    const {id,status}=object;
    this.updateProductInfoById({id,status})
  },
  onSettings(){
    this.settingsOrnClear(true)
  },
  onClear(){
    this.settingsOrnClear()
  },
  settingsOrnClear(flag){
    for (let skuFormTemplateKey in this.skuFormTemplate){
      this.tableBodyTemplate.forEach(item =>{
        for (let itemKey in item){
          if (skuFormTemplateKey===itemKey){
            if (flag){
              item[itemKey]=this.skuFormTemplate[skuFormTemplateKey]
            }else{
              item[itemKey]='';
            }
          }
        }
      });
    }
  },
  changeRuleInfoListByRuleId(object){
    this.tableColumnHeaderTemplate=[]
    this.tableBodyTemplate=[]
    console.log(object);
    let ruleInfo=null;
    this.ruleInfoList.forEach(item=>{
      if (object==item.id){
        ruleInfo=item;
      }
      if (null==ruleInfo){
        return;
      }
    })
    let ruleAttrJson = JSON.parse(ruleInfo.ruleAttr);
    ruleAttrJson.forEach((ruleAttr,index)=>{
      this.tableColumnHeaderTemplate.push({'prop':`xxx${index}`,'label':ruleAttr.ruleType})
    });

    const cartesian=(ruleAttrJson,index,current) =>{
      if (index ===ruleAttrJson.length){
        this.tableBodyTemplate.push({ ...current});
        return;
      }
      for (let i=0;i<ruleAttrJson[index].ruleAttrList.length;i++){
        current[`xxx${index}`]=ruleAttrJson[index].ruleAttrList[i];
        current['image']="";
        cartesian(ruleAttrJson,index+1,{ ...current});
      }
    };
    cartesian(ruleAttrJson,0,{});
    this.tableBodyTemplate.forEach(item=>{
      let  sku=[];
      for (let itemKey in item) {
        if(itemKey.indexOf('xxx')>-1){
          sku.push(item[itemKey])
        }
      }
      sku=sku.join(",")
      item['sku']=sku
    })
    this.tableColumnHeaderTemplate.push(
        {prop:'stock',label:'商品库存'},
        {prop:'price',label:'商品价格'},
        {prop:'purchasePrice',label:'商品进价'},
        {prop:'sellingPrice',label:'商品售价'},
        {prop:'image',label:'商品图片'},
        {prop:'number',label:'编号'},
        {prop:'weight',label:'重量'},
        {prop:'volume',label:'体积'},
    )
    console.log(ruleInfo);
  },
  initListRuleInfo(){
    let params = {
      status: 0
    }
    listRuleInfo(params).then(res => {
      if (200 == res.code) {
        this.ruleInfoList = res.data.rows
      }
    })
  },
  initCategoryList() {
    listAll7().then(response => {
      if (200 == response.code) {
        this.categoryList = response.data
      }
    })
  },

  initBrandList() {
    let params = {
      status: 0
    }
    listBrandList(params).then(response => {
      if (200 == response.code) {
        this.brandList = response.data.rows
      }
    })
  },
  pre() {
    this.active--;
  },
  next() {
    this.active++;
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询商品信息列表 */
function getList() {
  loading.value = true;
  listProductInfo(queryParams.value).then(response => {
    productInfoList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    productDesc: null,
    type: null,
    typeIds: null,
    img: null,
    carouselImages: null,
    commentCount: null,
    collectCount: null,
    brand: null,
    status: null,
    unit: null,
    keywords: null,
    ruleId: null,
    revision: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    step: null
  };
  proxy.resetForm("productInfoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加商品信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProductInfo(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商品信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productInfoRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProductInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProductInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商品信息编号为"' + _ids + '"的数据项？').then(function() {
    return delProductInfo(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('product/productInfo/export', {
    ...queryParams.value
  }, `productInfo_${new Date().getTime()}.xlsx`)
}

getList();
</script>
